package dfbz.线程通信;

public class Shower {
    private Integer flag=1;
    private Object obj=new Object();
    public void shower1() throws InterruptedException {
        while (true){
            synchronized (obj) {
                while (flag != 1) {
                    obj.wait();//等待并释放锁
                }
                Thread.sleep(1000);
                System.out.print("我");
                System.out.print("是");
                System.out.print("中");
                System.out.print("国");
                System.out.print("人");
                System.out.println();
                flag=2;
                obj.notifyAll();//唤醒所有线程
            }
        }
    }
    public void shower2() throws InterruptedException {
        while (true){
            synchronized (obj) {
                while (flag != 2) {
                    obj.wait();//等待并释放锁
                }
                Thread.sleep(1000);
                System.out.print("范");
                System.out.print("我");
                System.out.print("中");
                System.out.print("华");
                System.out.print("者");
                System.out.println();
                flag=3;
//                obj.notify();//随机唤醒一个线程
                obj.notifyAll();//唤醒所有线程
            }
        }
    }
    public void shower3() throws InterruptedException {
        while (true){
            synchronized (obj) {
                while (flag != 3) {
                    obj.wait();//等待并释放锁
                }
                Thread.sleep(1000);
                System.out.print("虽");
                System.out.print("远");
                System.out.print("必");
                System.out.print("诛");
                System.out.println();
                flag=1;
                obj.notifyAll();//唤醒所有线程
            }
        }
    }
}
